<?php
//缩图片自动生成函数，来源支持bmp、gif、jpg、png
//但生成的小图只用jpg或png格式
function makethumb($srcFile,$toW=240,$toH=240,$toFile="")
{
	if($toFile=="")
	{
		$toFile = $srcFile.'.thumb.jpg';
	}
	$info = "";
	
	$im = '';
	if($srcInfo = GetImageSize($srcFile,$info)) {
		if($srcInfo[2] == 1) {
			if(function_exists("imagecreatefromgif")) {
				$im = imagecreatefromgif($srcFile);
			}
		} elseif($srcInfo[2] == 2) {
			if(function_exists("imagecreatefromjpeg")) {
				$im = imagecreatefromjpeg($srcFile);
			}
		} elseif($srcInfo[2] == 3) {
			if(function_exists("imagecreatefrompng")) {
				$im = imagecreatefrompng($srcFile);
			}
		}
	}
	$srcW=ImageSX($im);//原图片宽
	$srcH=ImageSY($im);//原图片高
	if($srcW<=$toW && $srcH<=$toH )
	{
		$result = copy($srcFile,$toFile)?true:false;
		return $result;
	}
	$toWH=$toW/$toH; //thumb 的宽高比
	$srcWH=$srcW/$srcH;//原图的宽高比
	if($toWH<=$srcWH)
	{
		$ftoW=$toW;
		$ftoH=$ftoW*($srcH/$srcW);
	}
	else
	{
		$ftoH=$toH;
		$ftoW=$ftoH*($srcW/$srcH);
	}
	if($srcW>$toW||$srcH>$toH)
	{
		if(function_exists("imagecreatetruecolor"))
		{
			@$ni = imagecreatetruecolor($ftoW,$ftoH);
			if($ni)
			{
				imagecopyresampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
			else
			{
				$ni=imagecreate($ftoW,$ftoH);
				imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
		}
		else
		{
			$ni=imagecreate($ftoW,$ftoH);
			imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		}
		switch ($srcInfo[2])
		{
			case 1:
				imagegif($ni,$toFile);
				break;
			case 2:
				imagejpeg($ni,$toFile,85);
				break;
			case 3:
				imagepng($ni,$toFile);
				break;
			default:
				return false;
		}
		imagedestroy($ni);
	}

	imagedestroy($im);
	return true;
}
?>